package top.aigoo.project01.controller.shopadmin;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import top.aigoo.project01.entity.Product;
import top.aigoo.project01.entity.ProductCategory;
import top.aigoo.project01.entity.Shop;
import top.aigoo.project01.entity.dto.ImageHolder;
import top.aigoo.project01.entity.dto.ProductCategoryExecution;
import top.aigoo.project01.entity.dto.ProductExecution;
import top.aigoo.project01.enums.ProductCategoryEnum;
import top.aigoo.project01.enums.ProductStateEnum;
import top.aigoo.project01.service.ProductCategoryService;

import top.aigoo.project01.service.ProductService;
import top.aigoo.project01.utils.CodeUtil;
import top.aigoo.project01.utils.HttpServletRequestUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: product 商品controller接口
 * @Author: Mr.OYSHUO.欧阳大叔  mail:1642302522@qq.com
 * @Version 1.0.0
 * @Date: 2021/8/28 16:42
 */
@Controller
@RequestMapping("/shopadmin")
public class ProductManagementController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCategoryService productCategoryService;
    //支持上传商品详情图的最大数量
    private static final int IMAGEMAXCOUNT = 6;

    /**
     * 根据商品id获取商品信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getproductbyid", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getProductById(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();

        long productId = HttpServletRequestUtil.getLong(request, "productId");
        //非空判断
        if (productId > -1) {
            //获取商品信息
            Product product = productService.getProductById(productId);
            List<ProductCategory> productCategoryList = null;
            //获取该店铺下的商品类别列表
            ProductCategoryExecution pe = productCategoryService.queryByShopId(product.getShop().getShopId());
            if (pe.getState() == ProductCategoryEnum.SUCCESS.getState()) {
                productCategoryList = pe.getProductCategoryList();
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", "获取商品类型出错!");
            }

            modelMap.put("product", product);
            modelMap.put("productCategoryList", productCategoryList);
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "empty pageSize or pageIndex or shopId");
        }
        return modelMap;
    }

    /**
     * 修改商品信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyproduct", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> modifyProduct(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //商品编辑时候调用还是上下架操作的时候调用
        //如果是前者就进行验证码判断，如果是后者就跳过验证码的判断
        boolean statusChange = HttpServletRequestUtil.getBoolean(request, "statusChange");
        // 验证码判断
        if (!statusChange && !CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "输入了错误的验证码");
            return modelMap;
        }
        //接收前端参数的变量初始化，包含商品，缩略图，详情图列表实体类
        ObjectMapper mapper = new ObjectMapper();
        Product product = null;
        String productStr = HttpServletRequestUtil.getString(request, "productStr");
        MultipartHttpServletRequest multipartRequest = null;
        CommonsMultipartFile thumbnail = null;
        List<CommonsMultipartFile> productImgs = new ArrayList<CommonsMultipartFile>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //如果请求中存在文件流，那么就取出相关文件(包括缩略图和详情图)
        if (multipartResolver.isMultipart(request)) {
            multipartRequest = (MultipartHttpServletRequest) request;
            thumbnail = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
            // 取出详情图列表并构建 List<CommonsMultipartFile>
            for (int i = 0; i < IMAGEMAXCOUNT; i++) {
                CommonsMultipartFile productImg = (CommonsMultipartFile) multipartRequest
                        .getFile("productImg" + i);
                if (productImg != null) {
                    productImgs.add(productImg);
                }else {
                    //若取出的第i个详情图片文件流为空，则终止循环
                    break;
                }
            }
        }
        try {
            product = mapper.readValue(productStr, Product.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }

        if (product != null) {
            try {
                Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
                product.setShop(currentShop);
                ProductExecution pe = productService.modifyProduct(product, thumbnail, productImgs);
                if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
                    modelMap.put("success", true);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", pe.getStateInfo());
                }
            } catch (RuntimeException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
                return modelMap;
            }

        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入商品信息");
        }
        return modelMap;
    }

    /**
     * 获取当前商店下的所有商品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/listproductsbyshop", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> listProductsByShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //初始化接收数据
        int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex");
        int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
        Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");

        if ((pageIndex > -1) && (pageSize > -1) && (currentShop != null)
                && (currentShop.getShopId() != null)) {
            long productCategoryId = HttpServletRequestUtil.getLong(request, "productCategoryId");
            String productName = HttpServletRequestUtil.getString(request, "productName");
            Product productCondition = compactProductCondition4Search(
                    currentShop.getShopId(), productCategoryId, productName);

            ProductExecution pe = productService.getProductList(productCondition, pageIndex, pageSize);

            modelMap.put("productList", pe.getProductList());

            modelMap.put("count", pe.getCount());

            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "empty pageSize or pageIndex or shopId");
        }

        return modelMap;
    }

    /**
     * 添加商品 接口  /shopadmin/addproduct/
     *
     * @param request 包含product、缩略图、详情图列表的请求
     * @return
     */
    @RequestMapping(value = "/addproduct", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addProduct(HttpServletRequest request) {
        //1.初始化
        HashMap<String, Object> modelMap = new HashMap<>();
        //2,验证码校验
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "输入了错误的验证码");
            return modelMap;
        }
        //3.接收前端提交的请求，包括商品、缩略图、详情图列表实体类
        CommonsMultipartFile thumbnail = null;//产品缩略图
        List<CommonsMultipartFile> productImgs = new ArrayList<CommonsMultipartFile>();// 产品详情图列表
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = null;
        //4.从请求中接收缩略图和产品详情图列表
        try {
            // 如果请求中存在文件流,则取出相关的文件(包括缩略图和详情图)
            if (multipartResolver.isMultipart(request)) {
                multipartRequest = (MultipartHttpServletRequest) request;
                //取出缩略图
                thumbnail = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
                //取出详情图列表,最多支持六张图片上传
                for (int i = 0; i < IMAGEMAXCOUNT; i++) {
                    CommonsMultipartFile productImg = (CommonsMultipartFile) multipartRequest.getFile("productImg" + i);
                    if (productImg != null) {
                        //文件流不为空则将其加入到List
                        productImgs.add(productImg);
                    } else {
                        //如果取出的第i个详情图片文件流为空，则终止循环
                        break;
                    }
                }
            }
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }
        //5.接收前端的product并使用jackson解析pojo对象
        String productStr = HttpServletRequestUtil.getString(request, "productStr");
        Product product = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            product = mapper.readValue(productStr, Product.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }
        //6.开始调用service处理请求 若product信息、缩略图、详情图列表为非空，则开始进行商品添加操作
        if (product != null && thumbnail != null && productImgs.size() > 0) {
            try {
                //从session中获取当前店铺的id并赋值给product,减少对前端的依赖
                Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
                product.setShop(currentShop);
                //构建缩略图的ImageHolder
                ImageHolder thumbnailHolder = new ImageHolder(thumbnail.getOriginalFilename(), thumbnail.getInputStream());
                //构建详情图列表的List<ImageHolder>实例
                List<ImageHolder> imageHolderList = new ArrayList<>();
                for (CommonsMultipartFile productImg : productImgs) {
                    ImageHolder imageHolder = new ImageHolder(productImg.getOriginalFilename(), productImg.getInputStream());
                    imageHolderList.add(imageHolder);
                }
                //执行添加操作
                ProductExecution pe = productService.addProduct(product, thumbnailHolder, imageHolderList);
                if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
                    modelMap.put("success", true);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", pe.getStateInfo());
                }
            } catch (RuntimeException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
                return modelMap;
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
                return modelMap;
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "商品信息为空,请输入商品信息");
        }
        return modelMap;
    }

    /**
     * 拼装product实例
     *
     * @param shopId
     * @param productCategoryId
     * @param productName
     * @return
     */
    private Product compactProductCondition4Search(long shopId,
                                                   long productCategoryId, String productName) {
        Product productCondition = new Product();

        Shop shop = new Shop();
        shop.setShopId(shopId);
        productCondition.setShop(shop);

        if (productCategoryId != -1L) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setProductCategoryId(productCategoryId);
            productCondition.setProductCategory(productCategory);
        }

        if (productName != null) {
            productCondition.setProductName(productName);
        }

        return productCondition;
    }
}
